package cn.yuysaln.domain.strategy.service.armory;

import cn.yuysaln.domain.strategy.model.entity.StrategyAwardEntity;
import cn.yuysaln.domain.strategy.model.entity.StrategyEntity;
import cn.yuysaln.domain.strategy.model.entity.StrategyRuleEntity;
import cn.yuysaln.domain.strategy.repository.IStrategyRepository;
import cn.yuysaln.types.common.Constants;
import cn.yuysaln.types.enums.ResponseCode;
import cn.yuysaln.types.exception.AppException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.security.SecureRandom;
import java.util.*;

/**
 * 初始化策略: 既装配也能抽奖
 */

@Service
public class StrategyArmoryDispatch implements IStrategyArmory, IStrategyDispatch {
    @Resource
    private IStrategyRepository repository;

    /**
     * 总装配方法，包含了权重装配
     *
     * @param strategyId 策略ID
     * @return
     */
    @Override
    public boolean assembleLotteryStrategy(Long strategyId) {

        //查询该策略下的所有奖品
        List<StrategyAwardEntity> strategyAwardEntities = repository.queryStrategyAwardList(strategyId);

        //缓存库存信息
        for (StrategyAwardEntity strategyAwardEntity : strategyAwardEntities) {
            Integer awardId = strategyAwardEntity.getAwardId();
            Integer awardCount = strategyAwardEntity.getAwardCount();
            cacheStrategyAwardCount(strategyId, awardId, awardCount);
        }
        //装配概率表
        assembleLotteryStrategy(String.valueOf(strategyId), strategyAwardEntities);

        //权重过滤
        //查看该策略是否配置了规则
        StrategyEntity strategyEntity = repository.queryStrategyEntityByStrategyId(strategyId);
        String ruleWeight = strategyEntity.getRuleWeight();
        if (null == ruleWeight) return true;

        //配置了rule_Models,需要查看具体值，再查到具体的rule对象
        StrategyRuleEntity strategyRuleEntity = repository.queryStrategyRule(strategyId, ruleWeight);
        if (null == strategyRuleEntity) {
            //配置了权重的规则，但是权重的值确实空
            throw new AppException(ResponseCode.STRATEGY_RULE_WEIGHT_IS_NULL.getCode(), ResponseCode.STRATEGY_RULE_WEIGHT_IS_NULL.getInfo());
        }


        //拿到rule对象的value属性,如 4000：102，103，104  5000：102，103，104，105，106
        Map<String, List<Integer>> ruleWeightValueMap = strategyRuleEntity.getRuleWeightValues();
        //得到每个范围，分别装配
        Set<String> keys = ruleWeightValueMap.keySet();
        for (String key : keys) {
            //具体范围下可以解锁的奖品id
            List<Integer> ruleWeightValues = ruleWeightValueMap.get(key);
            //从所有的奖品中过滤出上方可以解锁的id
            ArrayList<StrategyAwardEntity> strategyAwardEntitiesClone = new ArrayList<>(strategyAwardEntities);
            strategyAwardEntitiesClone.removeIf(entity -> !ruleWeightValues.contains(entity.getAwardId()));
            //把所有过滤表全部装配
            assembleLotteryStrategy(String.valueOf(strategyId).concat("_").concat(key), strategyAwardEntitiesClone);
        }
        return true;

    }

    @Override
    public boolean assembleLotteryStrategyByActivityId(Long activityId) {
        Long strategyId = repository.queryStrategyIdByActivityId(activityId);
        return assembleLotteryStrategy(strategyId);
    }

    private void cacheStrategyAwardCount(Long strategyId, Integer awardId, Integer awardCount) {
        String cacheKey = Constants.RedisKey.STRATEGY_AWARD_COUNT_KEY + strategyId + Constants.UNDERLINE + awardId;
        repository.cacheStrategyAwardCount(cacheKey, awardCount);
    }


    @Override
    public Boolean subtractionAwardStock(Long strategyId, Integer awardId,Date endDateTime) {
        String cacheKey = Constants.RedisKey.STRATEGY_AWARD_COUNT_KEY + strategyId + Constants.UNDERLINE + awardId;
        return repository.subtractionAwardStock(cacheKey,endDateTime);
    }


    /**
     * 使用编码的方式给的奖品赋一个概率，得到查找表并缓存到redis
     *
     * @param strategyIdStr         策略ID的字符串
     * @param strategyAwardEntities 需要装配的奖品Entity
     */
    private void assembleLotteryStrategy(String strategyIdStr, List<StrategyAwardEntity> strategyAwardEntities) {
        //从每个奖品中拿到最小的概率，确认好精确度，最小概率是作为 划分的最小单位
        BigDecimal minAwardRate = strategyAwardEntities.stream()
                .map(StrategyAwardEntity::getAwardRate)
                .min(BigDecimal::compareTo)
                .orElse(BigDecimal.ZERO);

        //得到概率总和
        BigDecimal rateSum = strategyAwardEntities.stream()
                .map(StrategyAwardEntity::getAwardRate)
                .reduce(BigDecimal.ZERO, BigDecimal::add);


        //以得到的 最小概率作为划分单位，把概率总和划分
        BigDecimal rateRange = rateSum.divide(minAwardRate, 0, RoundingMode.CEILING);

        //上方得到的是数组的大小，然后根据每个奖品的（概率 * 大小）   得到一共要占的位置数量，最后填入奖品的id
        ArrayList<Integer> strategyAwardSearchRateTables = new ArrayList<>(rateRange.intValue());
        for (StrategyAwardEntity strategyAward : strategyAwardEntities) {
            Integer awardId = strategyAward.getAwardId();
            BigDecimal awardRate = strategyAward.getAwardRate();
            for (int i = 0; i < rateRange.multiply(awardRate).setScale(0, RoundingMode.CEILING).intValue(); i++) {
                strategyAwardSearchRateTables.add(awardId);
            }
        }

        //打乱顺序
        Collections.shuffle(strategyAwardSearchRateTables);

        //对上方得到的数组表作优化，添加索引，直接Hash得到对应的奖品ID
        LinkedHashMap<Integer, Integer> shuffleStrategyAwardSearchRateTable = new LinkedHashMap<>();
        for (int i = 0; i < strategyAwardSearchRateTables.size(); i++) {
            shuffleStrategyAwardSearchRateTable.put(i, strategyAwardSearchRateTables.get(i));
        }

        //缓存
        repository.storeStrategyAwardSearchRateTable(strategyIdStr, shuffleStrategyAwardSearchRateTable.size(), shuffleStrategyAwardSearchRateTable);
    }


    @Override
    public Integer getRandomAwardId(Long strategyId) {
        //先拿到该转盘的概率范围
        int rateRange = repository.getRateRange(strategyId);

        //从范围内随机一个数字，从查找表查找奖品
        return repository.getStrategyAwardAssemble(String.valueOf(strategyId), new SecureRandom().nextInt(rateRange));
    }


    @Override
    public Integer getRandomAwardId(Long strategyId, String ruleWeightValue) {
        String key = String.valueOf(strategyId).concat("_").concat(ruleWeightValue);
        //先拿到该转盘的概率范围
        int rateRange = repository.getRateRange(key);

        //从范围内随机一个数字，从查找表查找奖品
        return repository.getStrategyAwardAssemble(key, new SecureRandom().nextInt(rateRange));

    }


}
